package com.iuie.ns.datum.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.iuie.ns.datum.service.IFileInfoService;
import com.iuie.ns.datum.service.IFileService;
import com.iuie.ns.datum.vo.FileInfoVO;
import com.iuie.ns.datum.vo.FileTagVO;
import com.iuie.ns.frame.config.AppConfigUtil;
import com.iuie.ns.frame.web.dataset.vo.Page;
import com.iuie.ns.frame.web.response.vo.ResponseInfo;

@RequestMapping("datum/file")
@Controller
public class FileController {
	
	public static final String MD_ACCESS = AppConfigUtil.getInstance().getProperty("markdown.upload.access");
	
	@Resource
	private IFileService fileService;
    
    @Resource
    private IFileInfoService fileInfoService;
	
	@RequestMapping
	public String index(){
		return "view-datum/file/fileList";
	}

	/**
	 * 根据文件标签查询文件列表
	 * @param page
	 * @param fileTag
	 * @return
	 * @date 2017年8月15日 上午10:52:00
	 */
	@RequestMapping(value="findByTag",produces="application/json; charset=utf-8")
	@ResponseBody
	public String FindByTag(Page page,FileTagVO fileTag){
		List<FileInfoVO> list = fileInfoService.findByTag(null,fileTag);
		
		ResponseInfo ri = new ResponseInfo();
		ri.setInfo(list);
		String json = ri.toJson();
		return json;
	}
	
	/**
	 * 文件上传
	 * @param file 上传的文件
	 * @param request http servlet request
	 * @param fileType 文件归属，blog/file
	 * @param func 上传完成后，要执行的js函数
	 * @return
	 * @date 2017年8月15日 上午10:51:17
	 */
	@RequestMapping(value="/doUpload",method=RequestMethod.POST)
	@ResponseBody
	public String doUploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request, String fileType, String func,
			String targetId){
		String json = null;
		try {
			String s = request.getParameter("immediately");
			Boolean immediately = s == null ? true : Boolean.valueOf(s);
			FileInfoVO fileInfo = fileService.addOneFile(file, immediately, fileType, targetId);
			ResponseInfo ri = new ResponseInfo();
			ri.setInfo(fileInfo);
			json = ri.toJson();
			// 将json加工为javascript能够识别的字符串
		} catch (IOException e) {
			json = ResponseInfo.errorJson(e.getMessage());
		}
		String jsJson = StringEscapeUtils.escapeJavaScript(json);
		String html = "<script type='text/javascript'>" + func + "('"+jsJson+"')</script>";
		return html;
	}
	
	/**
	 * markdown上传文件
	 * @param file
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value="markdown/doUpload",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> uploadFileForMarkdown(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, String targetId,
			HttpServletRequest request) throws IOException {
		Map<String, Object> map = new HashMap<>();
		FileInfoVO fileInfo = fileService.addOneFile(file, true, "markdown", targetId);
		map.put("success", 1);
		map.put("message", "上传成功！");
		map.put("url", MD_ACCESS + fileInfo.getFileName());
		return map;
	}
	
	/**
	 * 分页查询文件列表
	 * @param fileInfo 查询条件
	 * @param page 分页信息
	 * @return
	 * @date 2017年8月15日 上午10:54:10
	 */
	@RequestMapping(value="/findByPage",method=RequestMethod.GET)
	@ResponseBody
	public ResponseInfo findByPage(FileInfoVO fileInfo, Page page) {
	    List<FileInfoVO> list = fileInfoService.queryLst(page, fileInfo);
	    return ResponseInfo.successInfo(list, page);
	}
	
	@RequestMapping(value="/fileDelete/{fileId}",method=RequestMethod.GET)
	@ResponseBody
    public ResponseInfo fileDelete(@PathVariable("fileId") Long fileId){
        fileService.deleteFileById(fileId);
        return ResponseInfo.successInfo("删除文件成功！");
    }
	
    @RequestMapping(value="/updateDownloadCount/{fileId}/{row}",method=RequestMethod.GET)
    public @ResponseBody ResponseInfo updateDownloadCount(@PathVariable("fileId") Long fileId, @PathVariable("row") Integer row){
        fileInfoService.downloadFileById(fileId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("fileId", fileId);
        map.put("row", row);
        return ResponseInfo.successInfo("更新下载次数成功！", map);
    }
    
    @RequestMapping(value="/fileDownload",method=RequestMethod.GET)
    public void fileDownload(Long fileId, Boolean download, HttpServletResponse resp) throws IOException{
        fileService.fileDownload(fileId, download, resp);
    }
    
    /**
     * 重命名文件-index
     * @param fileId
     * @param fileName
     * @return
     */
    @RequestMapping(value="/rename/index/{fileId}",method=RequestMethod.GET)
    public String renameIndex(@PathVariable("fileId") Long fileId, HttpServletRequest request){
    	request.setAttribute("fileId", fileId);
    	FileInfoVO fileInfo = fileInfoService.findById(fileId);
    	request.setAttribute("oldFileName", FilenameUtils.getBaseName(fileInfo.getOriginalName()));
    	return "view-datum/file/rename";
    }
    
    /**
     * 文件重命名
     * @param fileId
     * @param fileName
     * @return
     */
    @RequestMapping(value="/rename/{fileId}",method=RequestMethod.POST)
    @ResponseBody
    public ResponseInfo rename(@PathVariable("fileId") Long fileId, String fileName){
    	String oldFileName = fileInfoService.renameFile(fileId, fileName); // 返回历史文件名
    	return ResponseInfo.successInfo("文件：【" + oldFileName + "】，重命名为：【" + fileName + "】成功！");
    }
    
    /**
     * 修复文件大小
     * @param fileId
     * @return
     */
    @RequestMapping(value="/repairFileSize/{fileId}",method=RequestMethod.GET)
    @ResponseBody
    public ResponseInfo repairFileSize(@PathVariable("fileId") Long fileId){
    	fileService.updateFileSizeAuto(fileId);
    	return ResponseInfo.successInfo("修复成功！");
    }
    
    /**
     * 打开文件夹
     * @param fileId
     * @return
     * @throws IOException 
     * @date 2018年6月7日上午8:35:42
     */
    @RequestMapping(value="open/folder/{fileId}", method=RequestMethod.POST)
    @ResponseBody
    public ResponseInfo openFolder(@PathVariable("fileId") Long fileId) throws Exception {
    	fileService.openFolder(fileId);
    	return ResponseInfo.successInfo("打开文件夹成功！");
    }
    
    /**
     * 打开文件
     * @param fileId
     * @return
     * @throws Exception
     * @date 2018年6月9日下午5:09:38
     */
    @RequestMapping(value="open/file/{fileId}", method=RequestMethod.POST)
    @ResponseBody
    public ResponseInfo openFile(@PathVariable("fileId") Long fileId) throws Exception {
    	fileService.openFile(fileId);
    	return ResponseInfo.successInfo("打开文件成功！");
    }
}
